import React, { PureComponent, Fragment } from "react"
import {
  Table,
  Input,
  InputNumber,
  Popconfirm,
  Form,
  Button,
  Divider,
  Tooltip,
  Select,
  message
} from "antd"
import isEqual from "lodash/isEqual"
import { connect } from "dva"
import { formatMessage } from "umi/locale"
import styles from "./TableStyle.less"

const FormItem = Form.Item
const EditableContext = React.createContext()

const EditableRow = ({ form, index, ...props }) => (
  <EditableContext.Provider value={form}>
    <tr {...props} />
  </EditableContext.Provider>
)

const EditableFormRow = Form.create()(EditableRow)

class EditableCell extends React.Component {
  getInput = () => {
    if (this.props.inputType === "number") {
      return (
        <InputNumber max={this.props.max} min={this.props.min} step={this.props.step} />
      )
    }
    if (this.props.inputType === "select") {
      {
        if (this.props.dataIndex == "joint_number") {
          return (
            <Select>
              <Select.Option value="2">两拼板</Select.Option>
              <Select.Option value="1">单拼板</Select.Option>
            </Select>
          )
        }
        if (this.props.dataIndex == "cropper_thickness") {
          return (
            <Select>
              <Select.Option value="0 ~ 0.33">0 ~ 0.33</Select.Option>
              <Select.Option value="0.34 ~ 1">0.34 ~ 1</Select.Option>
              <Select.Option value="1.1 ~ 1.5">1.1 ~ 1.5</Select.Option>
              <Select.Option value="1.6 ~ 2">1.6 ~ 2</Select.Option>
              <Select.Option value="2 ~">2 ~</Select.Option>
            </Select>
          )
        }

        if (this.props.dataIndex == "layout") {
          return (
            <Select>
              <Select.Option value="竖排">竖排</Select.Option>
              <Select.Option value="横排旋转">横排旋转</Select.Option>
            </Select>
          )
        }

        if (this.props.title == "易断板") {
          return (
            <Select>
              <Select.Option value="否">否</Select.Option>
              <Select.Option value="是">是</Select.Option>
            </Select>
          )
        }
      }
    }
    return <Input />
  }

  render() {
    const {
      editing,
      dataIndex,
      title,
      inputType,
      record,
      index,
      max,
      min,
      step,
      ...restProps
    } = this.props
    return (
      <EditableContext.Consumer>
        {(form) => {
          const { getFieldDecorator } = form
          return (
            <td {...restProps}>
              {editing ? (
                <FormItem style={{ margin: 0 }}>
                  {getFieldDecorator(dataIndex, {
                    rules: [
                      {
                        required: true,
                        message: "请输入" + `${title}!`
                      }
                    ],
                    initialValue: record[dataIndex]
                  })(this.getInput())}
                </FormItem>
              ) : (
                restProps.children
              )}
            </td>
          )
        }}
      </EditableContext.Consumer>
    )
  }
}

@connect(({ os }) => ({ os }))
class OrderForm extends React.Component {
  constructor(props) {
    super(props)
    this.state = { editingKey: "", order: {} }
    this.columns = [
      {
        title: "物料号",
        dataIndex: "order_id",
        width: "9.67%",
        editable: true,
        inputType: "string",
        key: "1"
      },
      {
        title: "批次号",
        dataIndex: "lotId",
        width: "9.67%",
        editable: true,
        inputType: "string",
        key: "2"
      },

      {
        title: "PNL长",
        dataIndex: "height",
        editable: true,
        width: "4.67%",
        max: 750,
        min: 1,
        step: 0.1,
        inputType: "number",
        key: "3"
      },
      {
        title: "PNL宽",
        dataIndex: "width",
        editable: true,
        width: "4.67%",
        min: 1,
        step: 0.1,
        inputType: "number",
        key: "4"
      },
      {
        title: "铜箔厚度",
        dataIndex: "cropper_thickness",
        editable: true,
        width: "4.67%",
        inputType: "select",
        key: "5"
      },
      {
        title: "第1刀留宽",
        dataIndex: "top_edge",
        editable: true,
        width: "5.27%",
        max: 50,
        min: 0,
        step: 1,
        inputType: "number",
        key: "6"
      },
      {
        title: "第2刀留宽",
        dataIndex: "left_edge",
        editable: true,
        width: "5.27%",
        max: 50,
        min: 0,
        step: 1,
        inputType: "number",
        key: "7"
      },
      {
        title: "第3刀留宽",
        dataIndex: "bottom_edge",
        editable: true,
        width: "5.27%",
        max: 50,
        min: 0,
        step: 1,
        inputType: "number",
        key: "8"
      },
      {
        title: "第4刀留宽",
        dataIndex: "right_edge",
        editable: true,
        width: "5.27%",
        max: 50,
        min: 0,
        step: 1,
        inputType: "number",
        key: "9"
      },

      {
        title: "识别高",
        dataIndex: "calc_height",
        editable: false,
        width: "4.67%",
        max: 750,
        min: 1,
        step: 0.1,
        inputType: "number",
        key: "10"
      },
      {
        title: "识别宽",
        dataIndex: "calc_width",
        editable: false,
        width: "4.67%",
        min: 1,
        step: 0.1,
        inputType: "number",
        key: "11"
      },

      {
        title: "易断板",
        dataIndex: "is_break",
        editable: true,
        width: "4.67%",
        inputType: "select",
        key: "12"
      },
      {
        title: "几拼板",
        dataIndex: "joint_number",
        editable: true,
        width: "4.67%",
        inputType: "select",
        key: "13"
      },
      {
        title: "排板",
        dataIndex: "layout",
        editable: true,
        width: "5.67%",
        inputType: "select",
        key: "14"
      },
      {
        title: "任务数量",
        dataIndex: "planCount",
        editable: true,
        width: "4.67%",
        max: 10000000,
        min: 0,
        step: 1,
        inputType: "number",
        key: "15"
      },
      {
        title: "已加工数量",
        dataIndex: "amount",
        editable: true,
        width: "4.67%",
        max: 10000000,
        min: 0,
        step: 1,
        inputType: "number",
        key: "16"
      },
      {
        title: formatMessage({ id: "app.produce.operate" }),
        key: "action",
        width: "8.67%",
        render: (text, record) => {
          const editable = this.isEditing(record)
          return (
            <div>
              {editable ? (
                <span>
                  <EditableContext.Consumer>
                    {(form) => (
                      <a
                        href="javascript:;"
                        onClick={() => this.saveOrder(form, record.key)}
                        style={{ marginRight: 8 }}
                      >
                        保存
                      </a>
                    )}
                  </EditableContext.Consumer>
                  <Popconfirm
                    title="确定取消吗"
                    onConfirm={() => this.cancel(record.key)}
                  >
                    <a>取消</a>
                  </Popconfirm>
                </span>
              ) : (
                <span>
                  <a onClick={() => this.edit(record.key)}>编辑</a>
                  <Divider type="vertical" />
                  <Popconfirm title="保存" onConfirm={() => this.deleteOrder(record.key)}>
                    <a>删除</a>
                  </Popconfirm>
                </span>
              )}
            </div>
          )
        }
      }
    ]
  }
  newMember = () => {
    if (true) {
      console.log("in newMember()")
      var myDate = new Date()
      const { dispatch } = this.props
      const newData = {
        key: myDate.getTime(),
        lotId: "lotDefault",
        width: 600,
        height: 600,
        cropper_thickness: "0~0.33",
        top_edge: 15,
        left_edge: 15,
        bottom_edge: 15,
        right_edge: 15,
        calc_height: 0,
        calc_width: 0,
        is_break: "否",
        layout: "竖排",
        joint_number: "2",
        planCount: 200,
        amount: 0
      }
      this.setState({ order: newData })
      const newServerOrder = [newData]
      this.edit(newData.key)
      dispatch({
        type: "os/clickAddOrder",
        payload: newServerOrder
      })
    }
  }
  isEditing = (record) => record.key === this.state.editingKey

  cancel = () => {
    this.setState({ editingKey: "" })
  }
  handleOnRow = (record) => {
    const { dispatch } = this.props
    return {
      onDoubleClick: (event) => {
        dispatch({
          type: "os/updateChooseOrder",
          payload: [record]
        })
      }
    }
  }
  saveOrder(form, key) {
    const { dispatch } = this.props
    const { order } = this.state
    console.log("order: ", order)
    form.validateFields((error, row) => {
      if (error) {
        return
      }
      const newData = { ...order, ...row, key: key }
      this.setState({ order: {} })
      this.edit("")
      dispatch({
        type: "os/saveOrder",
        payload: newData
      })
    })
  }

  deleteOrder(key) {
    const { dispatch } = this.props
    dispatch({
      type: "os/deleteOrder",
      payload: key
    })
  }

  edit(key) {
    this.setState({ editingKey: key })
  }

  render() {
    const { workingOrder, totalOrders, showTotalOrdersFlag } = this.props.os
    let showData
    if (showTotalOrdersFlag) {
      showData = totalOrders
    } else {
      showData = workingOrder
    }
    const components = {
      body: {
        row: EditableFormRow,
        cell: EditableCell
      }
    }

    const columns = this.columns.map((col) => {
      if (!col.editable) {
        return col
      }
      return {
        ...col,
        onCell: (record) => ({
          record,
          inputType: col.inputType,
          dataIndex: col.dataIndex,
          max: col.max,
          min: col.min,
          step: col.step,
          title: col.title,
          editing: this.isEditing(record)
        })
      }
    })

    return (
      <Fragment>
        <Table
          components={components}
          bordered
          dataSource={showData}
          pagination={showTotalOrdersFlag}
          columns={columns}
          rowClassName="editable-row"
          size={"small"}
          onRow={this.handleOnRow}
          footer={() =>
            workingOrder.length > 0 ? (
              <div style={{ marginTop: 10 }}>
                <span style={{ fontSize: 18 }}>
                  已选中：
                  <font style={{ color: "#FF0000" }}>{workingOrder[0].order_id}</font>
                </span>

                <Button
                  style={{ width: 200, marginLeft: 500, fontSize: 16 }}
                  onClick={this.newMember}
                  icon="plus"
                >
                  添加工单
                </Button>
              </div>
            ) : (
              <div>
                <span style={{ fontSize: 18 }}>请双击需要加工的工单：</span>
                <Button
                  style={{ width: 200, marginLeft: 500 }}
                  onClick={this.newMember}
                  icon="plus"
                >
                  添加工单
                </Button>
              </div>
            )
          }
        />
      </Fragment>
    )
  }
}

export default OrderForm
